import Request from '@/uni_modules/luch-request/index.js'
import FingerprintJS from '@fingerprintjs/fingerprintjs';
const getFingerprintJS = async()=>{
	try {
		const fp = await FingerprintJS.load();
		const { visitorId } = await fp.get();
		window.visitorId = visitorId
		console.log('设备指纹:', visitorId);
	} catch (error) {
		console.error('获取指纹失败:', error);
	}
}
getFingerprintJS()
const getTokenStorage = () => {
	let token = ''
	try {
		token ='Bearer '+ uni.getStorageSync('userToken')
	} catch (e) {}
	return token
}
const http = new Request()
http.setConfig((config) => {
	// #ifdef H5
	config.baseURL = process.env.NODE_ENV == 'development' ? 'https://saas.yuantoucloud.com/prod-api/' : location.origin+'/prod-api/',
	// config.baseURL = 'http://admin.yuantoucloud.com/prod-api/',
	// #endif
	// #ifndef H5
	config.baseURL = 'https://saas.yuantoucloud.com/prod-api/',
	// #endif
	config.header = {
		...config.header,
		'us':'app',
	}
	return config
})

// 请求之前拦截器
http.interceptors.request.use((config) => {
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	console.log('config',config);
	config.header = {
		...config.header,
		Authorization: getTokenStorage(),
		clientId: "ZdfPlQ1bRKEgpAnCjry6kyJDVnxqRP0tK",
	}
	config.data = {
		...config.data,
		deviceId:window.visitorId||'',
	}
	/*
	if (!token) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
		return Promise.reject(config)
	}
	 */
	return config
}, (config) => {
	return Promise.reject(config)
})
// 响应拦截
http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	const data = response.data;
	console.log('响应拦截',data);
	if (data.code !== 200&&data.code!=501&&data.code!=601) { // 服务端返回的状态码不等于200，则reject()
		uni.showToast({
			title: data.msg,
			icon:'none'
		});
		if (data.code == 10000) {
			uni.navigateTo({
				url: '/pages/user/login/login',
				success: res => {},
				fail: () => {},
				complete: () => {}
			});
		}
	}
	
	if(data.code==601&&!location.origin.includes('saas.yuantoucloud.com')){
		uni.redirectTo({
			url: '/pages/kongbai/kongbai',
			success: res => {},
			fail: () => {},
			complete: () => {}
		});
	}
	
	return data
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	console.log(response)
	return Promise.reject(response)
})

export {
	http
}